<template>
    <div class="app-container app-height">
        <div class="bg-white">
            <div class="header-content">
                <h3 class="code-title">配置统计规则</h3>
            </div>
            <div>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-form-item label="规则名称：" prop="jobName">
                        <el-col :span="11">
                            <el-input
                                v-model="form.jobName"
                                v-if="id === undefined || isEdit === 'true'"
                            ></el-input>
                            <span v-else v-text="form.jobName"></span>
                        </el-col>
                    </el-form-item>
                    <el-form-item
                        label="统计周期："
                        prop="statisticsPeriodType"
                    >
                        <el-col :span="11">
                            <el-select
                                v-model="form.statisticsPeriodType"
                                placeholder="请选择统计周期"
                                style="width:100%"
                                v-if="id === undefined || isEdit === 'true'"
                            >
                                <el-option
                                    v-for="key in Object.keys(
                                        statisticsPeriodOption
                                    )"
                                    :key="key"
                                    :label="statisticsPeriodOption[key]"
                                    :value="key"
                                ></el-option>
                            </el-select>
                            <span
                                v-else
                                v-text="
                                    statisticsPeriodOption[
                                        form.statisticsPeriodType
                                    ]
                                "
                            ></span>
                        </el-col>
                    </el-form-item>
                    <!-- TODO -->
                    <el-form-item label="统计时间：" prop="statisticsTime">
                        <el-col :span="11">
                            <el-time-picker
                                placeholder="选择时间"
                                v-model="form.statisticsTime"
                                style="width: 100%;"
                                format="HH:mm"
                                value-format="HH:mm"
                                v-if="id === undefined || isEdit === 'true'"
                            ></el-time-picker>
                            <span v-else v-text="form.statisticsTime"></span>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="统计内容：" prop="statisticsType">
                        <el-col :span="11">
                            <el-select
                                v-model="form.statisticsType"
                                placeholder="请选择统计内容"
                                style="width:100%"
                                v-if="id === undefined || isEdit === 'true'"
                            >
                                <el-option
                                    v-for="key in Object.keys(
                                        statisticsContentOption
                                    )"
                                    :key="key"
                                    :label="statisticsContentOption[key]"
                                    :value="key"
                                ></el-option>
                            </el-select>
                            <!-- todo -->
                            <span
                                v-else
                                v-text="
                                    statisticsContentOption[form.statisticsType]
                                "
                            ></span>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="统计规则描述：">
                        <el-col :span="11">
                            <el-input
                                type="textarea"
                                v-model="form.statisticsDescribe"
                                v-if="id === undefined || isEdit === 'true'"
                            ></el-input>
                            <span
                                v-else
                                v-text="form.statisticsDescribe"
                            ></span>
                        </el-col>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="bg-white">
            <div class="header-content">
                <h3 class="code-title">统计表单列表</h3>
                <el-button
                    type="primary"
                    size="small"
                    v-if="this.id === undefined || isEdit === 'true'"
                    @click="add"
                    >添加</el-button
                >
            </div>
            <el-table v-loading="tableLoading" :data="DataList" border>
                <el-table-column
                    label="表名称"
                    align="center"
                    prop="tableAlias"
                    width="199"
                    :show-overflow-tooltip="true"
                >
                    <!-- <template slot-scope="scope">
                        <a
                            href="javascript:;"
                            style="color:#409eff;"
                            @click="handleGoto(scope.row)"
                            >{{ scope.row.tableName }}</a
                        >
                    </template> -->
                </el-table-column>
                <el-table-column
                    label="表名称（英文）"
                    align="center"
                    width="199"
                    prop="tableName"
                    :show-overflow-tooltip="true"
                />
                <el-table-column
                    label="表单所属层级"
                    align="center"
                    prop="dirPath"
                    :show-overflow-tooltip="true"
                />
                <el-table-column
                    label="表单简介"
                    align="center"
                    width="199"
                    prop="comment"
                />
                <el-table-column
                    label="表单负责人"
                    align="center"
                    prop="managerName"
                    width="199"
                />
                <!-- 不需要 -->
                <!-- <el-table-column
                    label="操作"
                    align="center"
                    width="99"
                    v-if="this.id === undefined || isEdit === 'true'"
                >
                    <template slot-scope="scope">
                        <el-popconfirm
                            title="确定删除吗？"
                            @confirm="handleDelete(scope.row)"
                        >
                            <p
                                class="danger-simple-btn simple-btn"
                                plain
                                slot="reference"
                            >
                                删除
                            </p>
                        </el-popconfirm>
                    </template>
                </el-table-column> -->
            </el-table>
            <pagination
                v-if="0"
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getmyDataList"
            />
        </div>
        <el-row
            type="flex"
            justify="center"
            v-if="this.id === undefined || isEdit === 'true'"
            style="margin-top:20px"
        >
            <el-button
                type="primary"
                size="large"
                @click="submit"
                :loading="loading"
                >确定</el-button
            >
            <el-button type="default" size="large" @click="cancel"
                >取消</el-button
            >
        </el-row>
        <FormTreeModal ref="formTreeModalRef" @sure="formTreeModalSure" />
    </div>
</template>
<script>
import {
    getStatisticsRuleDetail,
    getStatisticsFormList,
    addorChangeStatisticsRule,
    getStatisticsPeriodOption,
    getStatisticsContentOption
} from "@/api/dataManagement/dataMonitor/dataStatistics";
import { groupUserList } from "@/api/dataManagement/system/group";
import { getHeight } from "@/utils/zkComm";
import FormTreeModal from "./modules/FormTreeModal.vue";
export default {
    name: "statistics",
    data() {
        return {
            // 遮罩层
            loading: false,
            tableLoading: false,
            // 用户表格数据
            morehandleValue: "",
            total: 0,
            mapHeight: undefined,
            DataList: [
                // {
                //     tableName: "测试table_log",
                //     tableAlias: "table_log",
                //     deptName: "数据仓库（CDM）>商保部门（SHB）",
                //     safeLevel: "1",
                //     totalRow: 1234421,
                //     updateTime: "2021-2-17",
                //     concern: true,
                //     id: 226,
                //     dirId: 20
                // },
                // {
                //     tableName: "测试table_log",
                //     tableAlias: "table_log",
                //     deptName: "数据仓库（CDM）>商保部门（SHB）",
                //     safeLevel: "1",
                //     totalRow: 1234421,
                //     updateTime: "2021-2-17",
                //     concern: false,
                //     id: 226,
                //     dirId: 20
                // }
            ],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 30,
                id: this.treeId // TODO
            },
            statisticsPeriodOption: {},
            statisticsContentOption: {},
            groupList: [],
            statusList: [
                {
                    label: "驳回",
                    value: "0"
                },
                {
                    label: "通过",
                    value: "1"
                },
                {
                    label: "申请中",
                    value: "2"
                },
                {
                    label: "已撤销",
                    value: "3"
                }
            ],
            form: {
                // name:"999999"
            },
            rules: {
                jobName: [
                    {
                        required: true,
                        message: "规则名称不能为空",
                        trigger: ["blur", "input", "change"]
                    }
                ],
                statisticsPeriodType: [
                    {
                        required: true,
                        message: "请选择统计周期不能为空",
                        trigger: ["blur", "change"]
                    }
                ],
                statisticsTime: [
                    {
                        required: true,
                        message: "统计时间不能为空",
                        trigger: ["blur", "change"]
                    }
                ],
                statisticsType: [
                    {
                        required: true,
                        message: "统计内容不能为空",
                        trigger: ["blur", "change"]
                    }
                ]
                // email: [
                //     {
                //         required: true,
                //         message: "邮箱地址不能为空",
                //         trigger: "blur"
                //     },
                //     {
                //         type: "email",
                //         message: "'请输入正确的邮箱地址",
                //         trigger: ["blur", "change"]
                //     }
                // ],
            },
            id: undefined,
            isEdit: false,
            treeId: [],
            pickerOption: {
                disabledDate: time => {
                    return Date.now() - 3600 * 1000 * 24 > time.getTime();
                }
            }
        };
    },
    components: {
        FormTreeModal
    },
    created() {
        // this.getlistGroup();
        this.id = this.$route.query.id;
        this.isEdit = this.$route.query.isEdit;
        // console.log("isEdit:",this.isEdit, this.isEdit == 'true')
        if (this.id !== undefined || this.isEdit === "true") {
            // TODO 拿详情
            this.getDetail();
        }
        this.getSelectOption();
        // if (this.id === undefined || this.isEdit === "true") {
        //     this.getSelectOption();
        // }
    },
    mounted() {
        this.mapHeight = getHeight(true);
    },
    methods: {
        dateChange: function() {
            var startAt = (new Date(this.date) * 1000) / 1000;
            if (startAt < Date.now()) {
                this.form.statisticsTime = new Date();
            }
        },
        getDetail() {
            // this.getmyDataList(true);
            this.loading = true;
            getStatisticsRuleDetail(this.id)
                .then(res => {
                    if (res.code !== 200) {
                        return;
                    }
                    this.form = res.data || {};
                    this.treeId = res.data?.tableIds || [];
                    // this.DataList = res.data?.dataList || [];
                    if (this.treeId.length > 0) {
                        this.getmyDataList(true);
                    }
                })
                .catch(err => {})
                .finally(() => {
                    this.loading = false;
                });
        },
        // TODO 获取taleList
        getmyDataList(fresh = false) {
            if (fresh === true) {
                this.queryParams.pageNum = 1;
            }
            this.tableLoading = true;
            // getStatisticsFormList({
            //     // ...this.queryParams,
            //     // ids: this.treeId
            //     ids: [1, 2, 3, 4, 5]
            // })
            getStatisticsFormList(this.treeId)
                .then(res => {
                    if (res.code !== 200) {
                        return;
                    }
                    this.DataList = res.data;
                    // this.total = res.total;
                })
                .catch(err => {})
                .finally(() => {
                    this.tableLoading = false;
                });
        },
        getSelectOption() {
            getStatisticsPeriodOption().then(res => {
                if (res.code !== 200) {
                    return;
                }
                this.statisticsPeriodOption = res.data || [];
            });
            getStatisticsContentOption().then(res => {
                if (res.code !== 200) {
                    return;
                }
                this.statisticsContentOption = res.data || [];
            });
        },
        handleDelete(row) {
            //  console.log("row:", row);
        },
        downloadHandle() {
            // this.download(res.msg);
        },
        //获取分组
        getlistGroup() {
            groupUserList().then(res => {
                this.groupList = res.data;
                this.groupList.unshift({ groupName: "本人", groupId: "" });
            });
        },
        handleGoto(row) {
            this.$router.push("/DMS/myData/logRecord/details?id=" + row.id);
        },
        uploadBtn() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 30,
                tableName: undefined,
                groupId: "",
                status: undefined
            };
            this.getmyDataList();
        },
        searchBtn() {
            this.getmyDataList();
        },
        add() {
            this.$refs.formTreeModalRef.show(this.treeId);
        },
        formTreeModalSure(id) {
            this.treeId = id;
            if(id.length > 0 ){
                this.getmyDataList(true);
            }
            // this.getmyDataList(true);
            // console.log("id:", id);
        },
        submit() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.treeId.length === 0) {
                        this.$message.warning("请选择需要统计表单");
                        return;
                    }
                    // 修改
                    if (this.isEdit === "true") {
                        this.loading = true;
                        addorChangeStatisticsRule({
                            id: this.id,
                            ...this.form,
                            // list: this.DataList,
                            tableIds: this.treeId
                        })
                            .then(res => {
                                if (res.code !== 200) {
                                    this.$message.error("修改失败");
                                }
                                this.$message.success("修改成功");
                                this.$router.back();
                            })
                            .catch(err => {
                                this.$message.error("修改失败");
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    } else {
                        // 新增
                        // let statisticsTime = this.form.statisticsTime;
                        // statisticsTime = this.parseTime(
                        //     new Date(statisticsTime),
                        //     "{h}:{i}"
                        // );
                        // console.log("statisticsTime:", statisticsTime);
                        this.loading = true;
                        addorChangeStatisticsRule({
                            ...this.form,
                            // list: this.DataList,
                            tableIds: this.treeId
                        })
                            .then(res => {
                                if (res.code !== 200) {
                                    this.$message.error("添加失败");
                                }
                                this.$message.success("添加成功");
                                this.$router.back();
                            })
                            .catch(err => {
                                this.$message.error("添加失败");
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }
                }
            });
        },
        cancel() {
            this.$router.back();
        }
    }
};
</script>

<style lang="scss" scoped>
/****
 reset element style
.

 */
.header-content {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .code-title {
        border-left: 4px solid #1183f8;
        padding-left: 10px;
        line-height: 20px;
        height: 20px;
        font-weight: 400;
        font-size: 18px;
        margin: 0 10px 0 0;
        color: #606266;
    }
    ::v-deep .el-button--small {
        height: 30px;
    }
}
.el-col-3 {
    width: 70px;
}
.el-col-2 {
    width: 96px;
    margin-right: 10px;
}
/****
 reset element style
.

 */
.app-container {
    padding: 20px;
}
.operation {
    height: 43px;
    line-height: 43px;
    margin-bottom: 20px;
    .search-select-parent {
        width: 320px;
    }
    .concern {
        margin-left: 10px;
    }
    .associa-select,
    .el-form-item {
        margin-right: 10px;
    }
    .search-btn {
        margin-right: 0px !important;
    }
}
.concern-icon {
    &:hover {
        cursor: pointer;
    }
}
</style>
